<script setup>
import { useRoute } from "vue-router";
import { ref, onMounted, onUnmounted } from "vue";
import { userStore } from "@/stores/userStore";
import { formatDate } from "@/utils/dateUtil";
import { interceptor } from "@/utils/interceptor";

const route = useRoute();
const userUserStore = userStore();
const userName = userUserStore.userName;
const account = userUserStore.account;
const examId = ref(route.params.examId);
const examState = ref("");
const isAddAsMistake = ref(false);
// 错题数据数组
const mistakeQuestions = ref([]);
// 倒计时相关
const timeLeft = ref(0); // 剩余时间（秒）
const countdownInterval = ref(null); // 定时器引用
const localStorageKeyStartTime = `examStartTime_${examId.value}`; // 本地存储键名



// 格式化剩余时间为 MM:SS
function formatTime(seconds) {
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  return `${String(minutes).padStart(2, "0")}:${String(remainingSeconds).padStart(2, "0")}`;
}

// 获取错题数据的函数
const getMistakeQuestions = async () => {
  const httpInstance = interceptor();
  try {
    const res = await httpInstance.post("/student/mistakeCollection/page", {
      id: userUserStore.id,
    });
    console.log(res.data);
    mistakeQuestions.value = res.data.data;
  } catch (err) {
    console.error("获取错题数据失败:", err);
  }
};

// 考试信息
const exam = ref({
  id: "",
  courseId: "",
  examName: "",
  duration: "",
  startTime: "",
  endTime: "",
  finalScore: "",
  passingPoint: "",
  state: "",
  examState: "",
});

// 题目分类
const singleQuestions = ref([]); // 单选题
const multiQuestions = ref([]); // 多选题
const judgmentQuestions = ref([]); // 判断题
const subjectiveQuestions = ref([]); // 主观题

// 用户作答状态
const selectedSingleAnswers = ref({}); // 单选题选中答案
const selectedMultiAnswers = ref({}); // 多选题选中答案
const selectedJudgmentAnswers = ref({}); // 判断题选中答案
const subjectiveAnswers = ref({}); // 主观题文本框答案

// 是否固定头部
const isHeaderFixed = ref(false);

// 计算剩余时间
function calculateTimeLeft() {
  if (exam.value.examState === 1) return 0;
  const examDurationInMinutes = parseInt(exam.value.duration, 10); // 获取考试时长（分钟）
  const savedStartTime = localStorage.getItem(localStorageKeyStartTime); // 获取保存的考试开始时间
  let timeLeftInSeconds;

  if (savedStartTime) {
    const startTime = new Date(savedStartTime);
    const elapsedTime = Date.now() - startTime.getTime(); // 已经过的时间（毫秒）
    const elapsedMinutes = elapsedTime / (1000 * 60); // 转换为分钟
    timeLeftInSeconds = Math.max(0, (examDurationInMinutes - elapsedMinutes) * 60); // 剩余时间（秒）
  } else {
    timeLeftInSeconds = examDurationInMinutes * 60; // 如果没有保存时间，则使用初始时间
  }

  return timeLeftInSeconds;
}

// 初始化倒计时
function startCountdown() {
  timeLeft.value = calculateTimeLeft();

  // if (timeLeft.value <= 0) {
  //   console.log("考试时间已结束");
  //   // submit();
  //   return;
  // }

  countdownInterval.value = setInterval(() => {
    if (timeLeft.value > 0) {
      timeLeft.value--; // 每秒减少1秒
    } else {
      clearInterval(countdownInterval.value); // 停止倒计时
      if (exam.value.examState === 0) {
        submit(); // 自动提交试卷
      }
    }
  }, 1000);
}

// 页面挂载时添加滚动监听和加载数据
onMounted(() => {
  window.addEventListener("scroll", handleScroll, true);
  const httpInstance = interceptor();

  // 查看错题
  getMistakeQuestions();

  httpInstance.get(`/student/exam/${userUserStore.id}/${examId.value}`).then((res) => {
    console.log("API 返回的数据:", res.data.data);

    if (!res.data.data || !Array.isArray(res.data.data.questions)) {
      console.error("数据格式错误: questions 不存在或不是数组");
      return;
    }

    // 填充考试信息
    exam.value.id = res.data.data.id;
    exam.value.courseId = res.data.data.courseId;
    exam.value.duration = res.data.data.duration;
    exam.value.endTime = formatDate(res.data.data.endTime);
    exam.value.examName = res.data.data.examName;
    exam.value.finalScore = res.data.data.finalScore;
    exam.value.passingPoint = res.data.data.passingPoint;
    exam.value.startTime = formatDate(res.data.data.startTime);
    exam.value.state = res.data.data.state;
    exam.value.examState = res.data.data.examState;
    //已提交
    if (exam.value.examState === 1) {
      timeLeft.value = 0; //倒计时归零
      localStorage.removeItem(localStorageKeyStartTime); //清除本地存储的考试开始时间
      console.log("时间为0", timeLeft.value);
      exam.value.state = 4;
    } else if (exam.value.examState === 0) {
      const savedStartTime = localStorage.getItem(localStorageKeyStartTime);

      if (!savedStartTime) {
        const startTime = new Date().toISOString();
        localStorage.setItem(localStorageKeyStartTime, startTime);
      }
    }

    // 启动倒计时
    startCountdown();

    // 分类题目
    res.data.data.questions.forEach((question) => {
      switch (question.type) {
        case 1: // 单选题
          singleQuestions.value.push({
            userId: userStore.id,
            examId: examId.value,
            question: question.id,
            title: question.topic,
            options: [
              question.optionA,
              question.optionB,
              question.optionC,
              question.optionD,
            ].filter(Boolean), // 过滤掉空值
            answer: question.answer, // 正确答案
          });
          break;
        case 2: // 多选题
          multiQuestions.value.push({
            question: question.id,
            title: question.topic,
            options: [
              question.optionA,
              question.optionB,
              question.optionC,
              question.optionD,
            ].filter(Boolean), // 过滤掉空值
            answer: question.answer.split(""), // 正确答案（多选题可能有多个答案）
          });
          break;
        case 3: // 判断题
          judgmentQuestions.value.push({
            question: question.id,
            title: question.topic,
            options: ["对", "错"],
            answer: question.answer, // 正确答案
          });
          break;
        case 4: // 主观题
          subjectiveQuestions.value.push({
            question: question.id,
            title: question.topic,
            answer: question.answer, // 正确答案
          });
          break;
        default:
          console.warn(`未知题目类型: ${question.type}`);
          break;
      }
    });

    // 填充用户已选答案
    res.data.data.selectedQuestions.forEach((selectedQuestion) => {
      const questionId = selectedQuestion.questionId;
      const selectedAnswer = selectedQuestion.selectQuestion;

      if (singleQuestions.value.some((q) => q.question === questionId)) {
        selectedSingleAnswers.value[questionId] = selectedAnswer;
      } else if (multiQuestions.value.some((q) => q.question === questionId)) {
        selectedMultiAnswers.value[questionId] = selectedAnswer.split("");
      } else if (judgmentQuestions.value.some((q) => q.question === questionId)) {
        selectedJudgmentAnswers.value[questionId] = selectedAnswer;
      } else if (subjectiveQuestions.value.some((q) => q.question === questionId)) {
        subjectiveAnswers.value[questionId] = selectedAnswer;
      } else {
        console.warn(`无法匹配的题目 ID: ${questionId}`);
      }
    });
  });
});

// 页面卸载时移除滚动监听和清除定时器
onUnmounted(() => {
  window.removeEventListener("scroll", handleScroll);
  if (countdownInterval.value) {
    clearInterval(countdownInterval.value);
  }
});

// 提交答案
const submit = async () => {
  timeLeft.value = 0;
  localStorage.removeItem(localStorageKeyStartTime);
  if (countdownInterval.value) {
    clearInterval(countdownInterval.value);
  }
  const allAnswers = [];
  let finalScore = 0; // 用户得分

  // 遍历单选题
  singleQuestions.value.forEach((question) => {
    const questionId = question.question.toString();
    const userAnswer = selectedSingleAnswers.value[questionId] || ""; // 如果未作答，默认为空字符串
    const isCorrect = question.answer === userAnswer;

    if (isCorrect) {
      finalScore += 5; // 假设每道题5分
    }

    allAnswers.push({
      userId: userUserStore.id,
      examId: examId.value,
      questionId,
      selectedQuestion: userAnswer, // 提交用户答案（可能为空）
    });
  });

  // 遍历多选题
  multiQuestions.value.forEach((question) => {
    const questionId = question.question.toString();
    const userAnswer = selectedMultiAnswers.value[questionId] || []; // 如果未作答，默认为空数组
    const correctAnswer = question.answer.sort().join(""); // 正确答案排序后拼接成字符串
    const userAnswerString = userAnswer.sort().join(""); // 用户答案排序后拼接成字符串
    const isCorrect = correctAnswer === userAnswerString;

    if (isCorrect) {
      finalScore += 5; // 假设每道题5分
    }

    allAnswers.push({
      userId: userUserStore.id,
      examId: examId.value,
      questionId,
      selectedQuestion: userAnswer.join(""), // 提交用户答案（可能为空）
    });
  });

  // 遍历判断题
  judgmentQuestions.value.forEach((question) => {
    const questionId = question.question.toString();
    const userAnswer = selectedJudgmentAnswers.value[questionId] || ""; // 如果未作答，默认为空字符串
    const isCorrect = question.answer === userAnswer;

    if (isCorrect) {
      finalScore += 5; // 假设每道题5分
    }

    allAnswers.push({
      userId: userUserStore.id,
      examId: examId.value,
      questionId,
      selectedQuestion: userAnswer, // 提交用户答案（可能为空）
    });
  });

  // 遍历主观题
  subjectiveQuestions.value.forEach((question) => {
    const questionId = question.question.toString();
    const userAnswer = subjectiveAnswers.value[questionId] || ""; // 如果未作答，默认为空字符串

    allAnswers.push({
      userId: userUserStore.id,
      examId: examId.value,
      questionId,
      selectedQuestion: userAnswer, // 提交用户答案（可能为空）
    });
  });

  console.log("allAnswers:", allAnswers);

  // 构造请求体
  const requestBody = {
    userId: userUserStore.id,
    examId: examId.value,
    finalScore, // 总分
    answers: allAnswers, // 所有答案（包括未作答的题目）
  };

  // 提交数据
  try {
    // 检查考试状态
    const httpInstance = interceptor();
    const res = await httpInstance.get(`/student/exam/${userUserStore.id}/${examId.value}`);
    if (res.data.data.examState === 2) {
      confirm("考试已截止！无法提交");
      exam.value.state = 5;
      return; // 提前退出
    }

    // 提交答案
    const submitRes = await httpInstance.post("/student/exam/submit", requestBody);
    if (submitRes.data.code === 1) {
      exam.value.state = 4;
      examState.value = 1;
      exam.value.finalScore = finalScore;
      console.log("用户得分:", finalScore);
    }
  } catch (err) {
    console.error("提交失败:", err);
  }
};

// 在 <script setup> 中添加以下方法
function selectSingleOption(questionId, optionIndex) {
  const selectedOption = String.fromCharCode(65 + optionIndex); // 将索引转换为字母 (A, B, C, D)
  selectedSingleAnswers.value[questionId] = selectedOption; // 更新选中答案
}

// 在 <script setup> 中添加以下方法
function toggleMultiOption(questionId, optionIndex) {
  const selectedOption = String.fromCharCode(65 + optionIndex); // 将索引转换为字母 (A, B, C, D)

  if (!selectedMultiAnswers.value[questionId]) {
    selectedMultiAnswers.value[questionId] = []; // 初始化为空数组
  }

  const currentIndex = selectedMultiAnswers.value[questionId].indexOf(selectedOption);

  if (currentIndex === -1) {
    // 如果未选中，则添加到选中列表
    selectedMultiAnswers.value[questionId].push(selectedOption);
  } else {
    // 如果已选中，则移除
    selectedMultiAnswers.value[questionId].splice(currentIndex, 1);
  }
}

// 在 <script setup> 中添加以下方法
function selectJudgmentOption(questionId, optionIndex) {
  const selectedOption = String.fromCharCode(65 + optionIndex); // 将索引转换为字母 (A, B)
  selectedJudgmentAnswers.value[questionId] = selectedOption; // 更新选中答案
}

//加入错题集
const addAsMistake = (question) => {
  const questionId = question.question;
  if (mistakeQuestions.value.some((q) => q.questionId === question.question)) {
    return;
  }
  const httpInstance = interceptor();
  httpInstance
    .post("student/mistakeCollection", {
      userId: userUserStore.id,
      questionId: question.question,
      examId: examId.value,
    })
    .then((res) => {
      console.log(res);
      mistakeQuestions.value.push({ questionId });
      alert("添加成功！");
    })
    .catch((err) => {
      console.error("提交失败:", err);
    });
};

// 滚动事件处理函数
const handleScroll = () => {
  const scrollY =
    window.scrollY || document.documentElement.scrollTop || document.body.scrollTop || 0;

  const viewportHeight = window.innerHeight;
  // console.log(scrollY, viewportHeight);

  if (scrollY > viewportHeight * 0.1) {
    isHeaderFixed.value = true;
  } else {
    isHeaderFixed.value = false;
  }
};
</script>

<template>
  <div :class="['head', { 'fixed-header': isHeaderFixed }]">
    <!-- 头部信息保持不变 -->
    <div class="stu_info">
      <div class="info-item">
        <span>准考号:{{ account }}</span>
        <span>考生姓名:{{ userName }}</span>
      </div>
    </div>
    <div class="exam_info">
      <div class="exam_name">{{ exam.examName }}</div>
      <div class="exam_footer">
        <span>考试总分: {{ exam.finalScore }}</span>
        <span>考试时间：{{ formatTime(timeLeft) }}</span>
      </div>
    </div>
    <div class="button">
      <el-button
        type="primary"
        size="large"
        @click="submit"
        :disabled="exam.state === 3 || exam.state === 4"
        :class="{ disabled: exam.state === 5 || exam.state === 4 }"
      >
        {{ exam.state === 5 ? "截止提交" : exam.state === 4 ? "已提交" : "交卷" }}
      </el-button>
    </div>
  </div>

  <!-- 单选题 -->
  <div class="select">
    <span class="word">一、单选题(每题只有一个正确答案)</span>
    <div v-for="question in singleQuestions" :key="question.question" class="question">
      <span class="title">{{ question.title }}</span>
      <div class="options">
        <div
          v-for="(option, optionIndex) in question.options"
          :key="optionIndex"
          class="option"
          @click="examState === 1 ? null : selectSingleOption(question.question, optionIndex)"
        >
          <div class="button-container">
            <button
              class="circle-button"
              :class="{
                selected:
                  selectedSingleAnswers[question.question] ===
                  String.fromCharCode(65 + optionIndex),
              }"
            >
              {{ String.fromCharCode(65 + optionIndex) }}
            </button>
          </div>
          <span class="description">{{ option }}</span>
        </div>

        <div v-if="exam.examState === 1" class="correct-answer">正确答案：{{ question.answer }}</div>
        <div v-if="exam.examState === 1">
          <el-button
            type="primary"
            style="margin-top: 0.5%"
            :disabled="mistakeQuestions.some((q) => q.questionId === question.question)"
            @click="addAsMistake(question)"
          >
            {{
              mistakeQuestions.some((q) => q.questionId === question.question)
                ? "已加入错题集"
                : "添加为错题"
            }}</el-button
          >
          <p v-if="isAddAsMistake">已添加进错题集</p>
        </div>
      </div>
    </div>
  </div>

  <!-- 多选题 -->
  <div class="select">
    <span class="word">二、多选题(每题有多个正确答案)</span>
    <div v-for="question in multiQuestions" :key="question.question" class="question">
      <span class="title">{{ question.title }}</span>
      <div class="options">
        <div
          v-for="(option, optionIndex) in question.options"
          :key="optionIndex"
          class="option"
          @click="examState === 1 ? null : toggleMultiOption(question.question, optionIndex)"
        >
          <div class="button-container">
            <button
              class="circle-button"
              :class="{
                selected: selectedMultiAnswers[question.question]?.includes(
                  String.fromCharCode(65 + optionIndex)
                ),
              }"
            >
              {{ String.fromCharCode(65 + optionIndex) }}
            </button>
          </div>
          <span class="description">{{ option }}</span>
        </div>
        <!-- <div v-if="exam.examState === 1" class="correct-answer">正确答案：{{ question.answer }}</div> -->
        <div v-if="exam.examState === 1" class="correct-answer">
          正确答案：{{ Array.isArray(question.answer) ? question.answer.join('') : question.answer }}
        </div>
        <div v-if="exam.examState === 1">
          <el-button
            type="primary"
            style="margin-top: 0.5%"
            :disabled="mistakeQuestions.some((q) => q.questionId === question.question)"
            @click="addAsMistake(question)"
          >
            {{
              mistakeQuestions.some((q) => q.questionId === question.question)
                ? "已加入错题集"
                : "添加为错题"
            }}
          </el-button>
        </div>
      </div>
    </div>
  </div>

  <!-- 判断题 -->
  <div class="select">
    <span class="word">三、判断题(每题只有一个正确答案)</span>
    <div v-for="question in judgmentQuestions" :key="question.question" class="question">
      <span class="title">{{ question.title }}</span>
      <div class="options">
        <div
          v-for="(option, optionIndex) in question.options"
          :key="optionIndex"
          class="option"
          @click="examState === 1 ? null : selectJudgmentOption(question.question, optionIndex)"
        >
          <div class="button-container">
            <button
              class="circle-button"
              :class="{
                selected:
                  selectedJudgmentAnswers[question.question] ===
                  String.fromCharCode(65 + optionIndex),
              }"
            >
              {{ String.fromCharCode(65 + optionIndex) }}
            </button>
          </div>
          <span class="description">{{ option }}</span>
        </div>
        <div v-if="exam.examState === 1" class="correct-answer">正确答案：{{ question.answer }}</div>
        <div v-if="exam.examState === 1">
          <el-button
            type="primary"
            style="margin-top: 0.5%"
            :disabled="mistakeQuestions.some((q) => q.questionId === question.question)"
            @click="addAsMistake(question)"
          >
            {{
              mistakeQuestions.some((q) => q.questionId === question.question)
                ? "已加入错题集"
                : "添加为错题"
            }}
          </el-button>
        </div>
      </div>
    </div>
  </div>

  <!-- 主观题 -->
  <div class="select">
    <span class="word">四、主观题(请在文本框中输入答案)</span>
    <div v-for="question in subjectiveQuestions" :key="question.question" class="question">
      <span class="title">{{ question.title }}</span>
      <div class="text-area">
        <textarea
          v-model="subjectiveAnswers[question.question]"
          placeholder="请输入您的答案..."
          rows="4"
          class="answer-textarea"
          :disabled="examState === 1"
        ></textarea>
        <div v-if="exam.examState === 1" class="correct-answer">参考答案：{{ question.answer }}</div>
        <div v-if="exam.examState === 1">
          <el-button
            type="primary"
            style="margin-top: 0.5%"
            :disabled="mistakeQuestions.some((q) => q.questionId === question.question)"
            @click="addAsMistake(question)"
          >
            {{
              mistakeQuestions.some((q) => q.questionId === question.question)
                ? "已加入错题集"
                : "添加为错题"
            }}
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.head {
  width: 100vw;
  height: 12vh;
  display: flex;
  flex-direction: row;
  border-bottom: 1px solid rgb(132, 132, 132);
  transition: all 0.3s ease; // 平滑过渡效果
  background-color: white;

  .stu_info {
    width: 30%;
    height: 100%;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-start;

    .info-item {
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      justify-content: center;
      width: 35%;
      padding-right: 10px;
      font-size: 120%;
      color: rgb(95, 95, 95);

      span {
        margin: 2px 0;
      }
    }
  }

  .exam_info {
    width: 60%;
    height: 100%;
    display: flex;
    flex-direction: column;

    .exam_name {
      margin-left: 23%;
      margin-top: 1.5%;
      font-size: 250%;
      font-weight: 600;
    }

    .exam_footer {
      margin-left: 20%;

      span {
        margin-right: 20%;
      }
    }
  }

  .button {
    width: 10%;
    height: 100%;
    padding-top: 2.5%;
    padding-left: 3%;
    .el-button {
      &.disabled {
        background-color: gray; // 禁用时的背景颜色
        color: white; // 禁用时的文字颜色
        cursor: not-allowed; // 鼠标悬停时显示禁止状态
        pointer-events: none; // 禁止点击
      }
    }
  }
}
.fixed-header {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 1000;
}
.select {
  margin-top: 2%;
  width: 100vw;

  .word {
    margin-left: 2%;
    font-size: 150%;
    font-weight: 600;
  }

  .question {
    display: flex;
    flex-direction: column;

    .title {
      margin-top: 1%;
      margin-left: 2%;
      font-size: 120%;
    }

    .options {
      display: flex;
      flex-direction: column;
      margin-left: 4%;

      .option {
        display: flex;
        flex-direction: row;
        align-items: center; // 垂直居中对齐
        margin-top: 1%; // 每个选项之间的间距
        cursor: pointer; // 鼠标悬停时显示手型

        .button-container {
          width: 2.5%;
          padding-top: 2.5%;
          position: relative;
          background-color: transparent;

          .circle-button {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            border-radius: 50%;
            color: rgb(19, 19, 19);
            font-size: 16px;
            font-weight: bold;
            border: 1px solid black;
            cursor: pointer;
            display: flex;
            justify-content: center;
            align-items: center;
            text-transform: uppercase;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            transition: background-color 0.3s ease;

            &.selected {
              background-color: rgb(73, 228, 252); // 选中时变为蓝色
              color: white; // 文字颜色变为白色
            }

            &.correct {
              background-color: rgb(98, 236, 98) !important; // 绿色高亮
              color: white;
            }
          }
        }

        .description {
          margin-left: 1%;
          font-size: 125%;
        }
      }
    }

    .text-area {
      margin-top: 1%;
      margin-left: 4%;

      .answer-textarea {
        width: 90%; // 宽度占父容器的90%
        padding: 10px; // 内边距
        font-size: 16px; // 字体大小
        border: 1px solid #ccc; // 边框颜色
        border-radius: 5px; // 圆角
        resize: none; // 禁止用户手动调整大小
        transition: border-color 0.3s ease; // 边框颜色平滑过渡

        &:focus {
          border-color: #007bff; // 聚焦时边框颜色变为蓝色
          outline: none; // 移除默认聚焦轮廓
        }
        &:disabled {
          background-color: #f5f5f5; // 禁用时背景颜色变灰
          color: #aaa; // 文字颜色变浅
        }
      }
    }
  }
  .correct-answer {
    margin-top: 1%;
    font-size: 14px;
    color: rgb(76, 212, 76);
    font-weight: bold;
  }
}
</style>
